/**
 * token验证 相关的路由
 */

const { ErrorModel } = require("../model/responseModel.js");

const jwt = require('jsonwebtoken')

const handleTokenRoute = (req, res) => {

  const method = req.method;

  // 需要放行的路由（在此添加）
  if ((method === "POST" && req.path === "/api/user/register") 
      || (method === "POST" && req.path === "/api/user/login")
    ) {
      return
  }

  const token = String(req.headers.authorization).split(' ')[1]
  
  try {
    // token解密，获取token存储的信息
    const tokenObj = jwt.verify(token, 'slowgoat')

    if (tokenObj === null || tokenObj.username === null) {
      return new ErrorModel("无效token", "", 401);
    }

  }catch(err) {
      // token验证失败直接返回token无效
      return new ErrorModel("无效token", "", 401);
  }
};

module.exports = handleTokenRoute;